package org.jeecg.modules.scm.service.impl;

import cfca.trustsign.common.vo.cs.EnterpriseTransactorVO;
import cfca.trustsign.common.vo.cs.EnterpriseVO;
import cfca.trustsign.demo.op.CfcaOp;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.modules.scm.entity.ScmCusInfo;
import org.jeecg.modules.scm.mapper.ScmCusInfoMapper;
import org.jeecg.modules.scm.service.IScmCusInfoService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

import static org.jeecg.modules.scm.common.util.StringConversion.changeForFuzzy;

/**
 * @Description: scm_cus_info
 * @Author: jeecg-boot
 * @Date:   2021-10-22
 * @Version: V1.0
 */
@Service
public class ScmCusInfoServiceImpl extends ServiceImpl<ScmCusInfoMapper, ScmCusInfo> implements IScmCusInfoService {

    @Resource
    private ISysBaseAPI iSysBaseAPI;

    //根据客户号获取客户名称

    @Override
    public String getNameByNo(String cusNo) {
        return baseMapper.selectById(cusNo).getCusName();
    }

    //根据客户名称获取客户号

    @Override
    public Integer getNoByName(String cusName) {
        QueryWrapper<ScmCusInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ScmCusInfo::getCusName, cusName);
        ScmCusInfo scmCusInfo = baseMapper.selectOne(queryWrapper);
        return scmCusInfo!=null?scmCusInfo.getCusNo():null;
    }

    //多字段查询

    @Override
    public List<ScmCusInfo> queryByFields(Map<String, Object> scmCusInfo) {
        QueryWrapper<ScmCusInfo> queryWrapper = new QueryWrapper();
        boolean flag = false;
        for(String key:scmCusInfo.keySet()){
            if(scmCusInfo.get(key)!=null){
                queryWrapper.eq(key,scmCusInfo.get(key));
                flag = true;
            }
        }
        if(!flag){
            return null;
        }
        List<ScmCusInfo> list = baseMapper.selectList(queryWrapper);
        return list;
    }

    //模糊查询

    @Override
    public List<ScmCusInfo> fuzzyQuery(String type, String value,String fields) {
        String res = changeForFuzzy(value);

        if(fields!= null&&!fields.isEmpty()){
            fields = type+","+fields;
        }else{
            fields = type;
        }
        QueryWrapper<ScmCusInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(fields).like(type, res);
        List<ScmCusInfo> list = baseMapper.selectList(queryWrapper);
        //List<String> result = getObjectProperty(list, type);
        return list;
    }

    @Override
    public List<Map<String, Object>> likeName(String key) {
        LambdaQueryWrapper<ScmCusInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(ScmCusInfo::getCusName, ScmCusInfo::getCusNo)
                .like(ScmCusInfo::getCusName, key);
        return baseMapper.selectMaps(queryWrapper);
    }

    @Override
    public String uploadAccessory(MultipartFile[] files,Integer cusNo) {
        //TODO CFCA验证客户
//        String url = CommonUtils.upload( file, "/cusInfo", CommonConstant.UPLOAD_TYPE_MINIO);
//        String path = URLUtil.getPath(url);
//        if(url==null){
//            throw new JeecgBootException("上传失败");
//        }
//        return path;
//        ScmCusInfo scmCusInfo = lambdaQuery().select(ScmCusInfo::getCusNo, ScmCusInfo::getAttachment).
//                eq(ScmCusInfo::getCusNo, cusNo).one();
//        if(scmCusInfo==null){
//            throw new JeecgBootException("客户不存在");
//        }
//        String attachment = scmCusInfo.getAttachment();
        if(files==null||files.length<=0){
            throw new JeecgBootException("未上传文件");
        }
        ScmCusInfo scmCusInfo = lambdaQuery().select(ScmCusInfo::getCusNo,ScmCusInfo::getCusName, ScmCusInfo::getAttachment)
                .eq(ScmCusInfo::getCusNo, cusNo)
                .one();
        if(scmCusInfo==null) {
            throw new JeecgBootException("客户不存在");
        }
        String urls = scmCusInfo.getAttachment();
        for(MultipartFile file:files){
            String url = CommonUtils.upload( file, "/cusInfo/"+scmCusInfo.getCusName(), CommonConstant.UPLOAD_TYPE_MINIO);
            String path = URLUtil.getPath(url);
            if(!StringUtils.isNotBlank(path)) {
                continue;
            }
            if (StringUtils.isEmpty(urls)) {
                urls = path;
            } else {
                urls = urls + "," + path;
            }
        }
        scmCusInfo.setAttachment(urls);
        baseMapper.updateById(scmCusInfo);
        return urls;
    }
    /**
     * 根据客户信息进行cfca企业开户
     * **/
    @Override
    public ScmCusInfo ctreateEnterprise(ScmCusInfo scmCusInfo){
        EnterpriseVO enterprise = new EnterpriseVO();
        EnterpriseTransactorVO enterpriseTransactor = new EnterpriseTransactorVO();
        //企业
        enterprise.setEnterpriseName(scmCusInfo.getCusName());
        enterprise.setIdentTypeCode(scmCusInfo.getCertificateType());
        enterprise.setIdentNo(scmCusInfo.getCertificateNo().toString());
        enterprise.setMobilePhone(scmCusInfo.getContactPhone());
        enterprise.setLandlinePhone(scmCusInfo.getContactPhone());
//        enterprise.setEmail();
        enterprise.setAuthenticationMode("公安部");
        LoginUser user = null;
        //经理
        try {
            if(StringUtils.isNotBlank(scmCusInfo.getCusManage())){
                user = iSysBaseAPI.getUserByName(scmCusInfo.getCusManage());
            }
            else{
                user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            }


            enterpriseTransactor.setTransactorName(user.getUsername());
            enterpriseTransactor.setIdentTypeCode(user.getCredentialsType().toString());
            enterpriseTransactor.setIdentNo(user.getCredentialsNumber());

        }catch (Exception e){
            e.printStackTrace();
            throw new JeecgBootException("客户经理信息有误");
        }
        //添加信息
        scmCusInfo.setCusManage(user.getUsername());
        scmCusInfo.setPlatformAffiliation(user.getOrganization().getName());

        String res = CfcaOp.ctreateEnterprise(enterprise, enterpriseTransactor);
        JSONObject object = JSONObject.parseObject(res);
        Map<String,Object> map = JSON.toJavaObject(object, Map.class);
        if(map.containsKey("errorCode")){
            throw new JeecgBootException("开户失败："+map.get("errorMessage"));
        }
        return scmCusInfo;


    }



}
